#include "FileGroup.h"
#include "FileFormatter.h"
#include <windows.h>

FileGroup::FileGroup()
{
}

FileGroup::~FileGroup()
{
	Clear();
}


void FileGroup::Clear()
{
	File* file;
	std::list<File*>::iterator it;

	for (it = files.begin(); it != files.end(); ++it)
	{
		file = *it;

		delete file;
	}

	files.clear();
}

void FileGroup::FromDirectory(const File& dir)
{
	HANDLE searchHandle;
	WIN32_FIND_DATA fileInformation;


	Clear();

	if (!dir.DirectoryAttribute())
		throw "FileGroup: Cannot list non-directory";


	std::string formattedPath = dir.PathString() + "\\*";

	searchHandle = FindFirstFile(formattedPath.c_str(), &fileInformation);
	if (searchHandle == INVALID_HANDLE_VALUE)
		return;

	do
	{
		// Add every file to the group, except . and ..
		if (strcmp(fileInformation.cFileName, ".") && strcmp(fileInformation.cFileName, ".."))
		{
			File file( dir.PathString() + "\\" + fileInformation.cFileName );

			AddFile(file);
		}
	} while(FindNextFile(searchHandle, &fileInformation));


	FindClose(searchHandle);
}

void FileGroup::AddFile(const File& file)
{
	files.push_back(new File(file));
}


const std::string& FileGroup::ToString()
{
	std::list<File*>::const_iterator it;
	string.clear();

	//string += "drw-rw-rw-   1 user     group           0 Sep 27 06:49 .\r\n";
	//string += "drw-rw-rw-   1 user     group           0 Sep 27 06:49 ..\r\n";


	for (it = files.begin(); it != files.end(); ++it)
	{
		const File* file = *it;

		FileFormatter formatter(*file);

		string += formatter.FormattedString() + "\r\n";
	}

	return string;
}

bool FileGroup::ContainsFile(const File& file) const
{
	bool fileFound = false;
	std::list<File*>::const_iterator it;


	for (it = files.begin(); it != files.end(); ++it)
	{
		File* itfile = *it;

		if((*itfile).ContainsFile(file))
			fileFound = true;
	}

	return fileFound;
}